package com.kgc.easyshopping.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.pagehelper.PageInfo;
import com.kgc.easyshopping.config.AlipayConfig;
import com.kgc.easyshopping.dto.BizDto;
import com.kgc.easyshopping.entity.Detail;
import com.kgc.easyshopping.entity.Order;
import com.kgc.easyshopping.entity.Product;
import com.kgc.easyshopping.service.DetailService;
import com.kgc.easyshopping.service.OrderService;
import com.kgc.easyshopping.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@RestController
public class OrderController {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AlipayConfig ac;
    @Resource
    private OrderService orderService;
    @Resource
    private DetailService detailService;
    @Resource
    private ProductService productService;
    @Resource
    private RedisTemplate redisTemplate;//使用需要注入RedisTemplate

    @PostMapping("order")
    public PageInfo<Order> selectPageInfo(@RequestParam Map<String, Object> params){
        Map<String, Object> map = new HashMap<>();

        int pageNum =  Integer.parseInt((String) params.get("pageNum"));
        int pageSize = Integer.parseInt((String) params.get("pageSize"));
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);

        String serialnumber = (String) params.get("serialnumber");
        if(serialnumber!=null && serialnumber!=""){
            map.put("serialnumber",serialnumber);
        }
        String loginname = (String) params.get("loginname");
        if(loginname!=null && loginname!=""){
            map.put("loginname","%"+loginname+"%");
        }
        String userid = "18";
        map.put("userid",userid);

        PageInfo<Order>  pageInfo = orderService.selectPageInfo(map);
        List<Order> list = pageInfo.getList();
        for(Order order:list){
            if(order.getIsdel()!=1){
                String serialnumber1 = (String) redisTemplate.opsForValue().get(order.getSerialnumber());
                if(serialnumber==null || serialnumber==""){
                    order.setIsdel(2);
                    orderService.updateByPrimaryKeySelective(order);
                }
            }
        }

        BizDto<PageInfo> bizDto = new BizDto<PageInfo>();
        bizDto.setData(pageInfo);
        return bizDto.getData();
    }

    @PostMapping("myOrder")
    public PageInfo<Order> selectUserOrder(@RequestParam Map<String, Object> params){
        Map<String, Object> map = new HashMap<>();

        int pageNum =  Integer.parseInt((String) params.get("pageNum"));
        int pageSize = Integer.parseInt((String) params.get("pageSize"));
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);

        String userid = "18";
        map.put("userid",userid);
        PageInfo<Order>  pageInfo = orderService.selectUserOrder(map);
        List<Order> list = pageInfo.getList();
        for(Order order:list){
            if(order.getIsdel()!=1){
                String serialnumber = (String) redisTemplate.opsForValue().get(order.getSerialnumber());
                if(serialnumber==null || serialnumber==""){
                    order.setIsdel(2);
                    orderService.updateByPrimaryKeySelective(order);
                }
            }
        }

        BizDto<PageInfo> bizDto = new BizDto<PageInfo>();
        bizDto.setData(pageInfo);
        return bizDto.getData();
    }

    @PostMapping("close")
    @ResponseBody
    public boolean Close(String orderid){
        Order order = new Order();
        order.setOid(orderid);
        order.setIsdel(2);
        BizDto<Boolean> bizDto = new BizDto<Boolean>();
        bizDto.setData(orderService.updateByPrimaryKeySelective(order));
        return bizDto.getData();
    }

    //支付宝支付接口
    @RequestMapping("/zf")
    public void zf(HttpServletResponse response, HttpServletRequest request,String serialnumber,String money,String name) throws AlipayApiException, IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, ac.getApp_id(), AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数

        //PC版页面支付对象
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //设置同步回调地址
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        //设置异步回调地址
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//        redisTemplate.opsForValue().set("serialnumber",serialnumber);//存储
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = serialnumber;
        //付款金额，必填
        String total_amount = money;
        //订单名称，必填
        String subject = name+"的订单";
        //商品描述，可空
        String body ="简单的描述";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(result);//{content:+resutl}
        response.getWriter().close();
    }

    @RequestMapping("/notify_url")
    public void notify_url(HttpServletRequest request,HttpServletResponse response) throws IOException, AlipayApiException {
        System.out.println("异步回调开始执行");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<h1>支付完成  异步</h1>");
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                System.out.println("交易关闭！");
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
                String serialnumber = request.getParameter("out_trade_no");
                Order order = orderService.selectBySerialnumber(serialnumber);
                Order order1 = new Order();
                order1.setOid(order.getOid());
                order1.setIsdel(1);
                orderService.updateByPrimaryKeySelective(order1);
                System.out.println("付款完成！");
            }
            out.println("success");
        }else {//验证失败
//            String serialnumber = request.getParameter("out_trade_no");
//            orderService.selectBySerialnumber(serialnumber);
//            String serialnumber1 = (String) redisTemplate.opsForValue().get(serialnumber);
//            if(serialnumber1==null && serialnumber1==""){
//                Order order = orderService.selectBySerialnumber(serialnumber);
//                String orderid = order.getOid();
//                List<Detail> list = detailService.selectByOrderId(orderid);
//                for(Detail detail:list){
//                    String produvtId = detail.getProductid();
//                    Product product = productService.selectById(produvtId);
//                    product.setStock(product.getStock()+detail.getQuantity());
//
//                }
//            }
            out.println("fail");
            System.out.println("验证失败");
            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
        out.close();
        System.out.println("异步回调执行完成");
    }

}
